Q-2 Alternative 2: Android Activity Lifecycle (5 Marks)
Question
a) Explain key stages of Android activity lifecycle with neat sketch.
Answer
Android Activity Lifecycle Overview
The Android Activity Lifecycle defines the various states an activity goes through from creation to destruction, managed by the Android system to optimize performance and resource usage.
Activity Lifecycle Diagram
[Activity Launched]
|
▼
┌─────────────┐
│ onCreate() │ ◄─── Activity Created
└─────────────┘
|
▼
┌─────────────┐
│ onStart() │ ◄─── Activity Visible
└─────────────┘
|
▼
┌─────────────┐
│ onResume() │ ◄─── Activity Interactive
└─────────────┘
|
▼
┌─────────────┐
│ RUNNING │ ◄─── Activity Active
│ STATE │
└─────────────┘
|
▼ (Another activity comes to foreground)
┌─────────────┐
│ onPause() │ ◄─── Activity Partially Hidden
└─────────────┘
|
▼ (Activity completely hidden)
┌─────────────┐
│ onStop() │ ◄─── Activity Hidden
└─────────────┘
|
▼ (Activity no longer needed)
┌─────────────┐
│ onDestroy() │ ◄─── Activity Destroyed
└─────────────┘
|
▼
[Activity Terminated]
┌─────── Restart Paths ───────┐
│ │
│ onRestart() → onStart() │ ◄─── From Stopped State
│ │
│ onResume() │ ◄─── From Paused State
└─────────────────────────────┘
Detailed Lifecycle Stages
1. onCreate() - Activity Creation
Purpose: Initialize the activity and set up the user interface.
Characteristics:
- Called only once during activity lifetime
- Activity is being created
- Set up static content and initialize variables
- Not yet visible to user
Implementation:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialize UI components
TextView textView = findViewById(R.id.textView);
Button button = findViewById(R.id.button);
// Set up click listeners
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Handle button click
}
});
// Restore saved state if available
if (savedInstanceState != null) {
String savedText = savedInstanceState.getString("saved_text");
textView.setText(savedText);
}
}
Common Tasks:
- Set content view
- Initialize UI components
- Set up event listeners
- Restore saved instance state
- Initialize member variables
2. onStart() - Activity Becomes Visible
Purpose: Prepare the activity to become visible to the user.
Characteristics:
- Activity becomes visible but not interactive
- Called after onCreate() and before onResume()
- Can be called multiple times during activity lifetime
- Activity is in the foreground but behind another activity
Implementation:
@Override
protected void onStart() {
super.onStart();
// Start animations
startUIAnimations();
// Register broadcast receivers
IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
registerReceiver(batteryReceiver, filter);
// Initialize location services
if (locationManager != null) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
}
Common Tasks:
- Start animations
- Register broadcast receivers
- Initialize services that require visibility
- Refresh UI with latest data
3. onResume() - Activity Becomes Interactive
Purpose: Activity is now in the foreground and ready for user interaction.
Characteristics:
- Activity is fully visible and interactive
- Has focus and can receive user input
- This is the "running" state
- Called every time activity comes to foreground
Implementation:
@Override
protected void onResume() {
super.onResume();
// Resume camera preview
if (camera != null) {
camera.startPreview();
}
// Resume game or animation
if (gameEngine != null) {
gameEngine.resume();
}
// Start sensor monitoring
sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
// Update UI with fresh data
refreshUserInterface();
}
Common Tasks:
- Resume camera operations
- Start sensors and GPS
- Resume animations and games
- Refresh data from server
- Start timers and periodic tasks
4. onPause() - Activity Loses Focus
Purpose: Another activity is taking focus (partially covering this activity).
Characteristics:
- Activity is partially obscured
- Should pause ongoing operations
- May be killed by system if memory is low
- Should save critical user data
Implementation:
@Override
protected void onPause() {
super.onPause();
// Pause camera preview
if (camera != null) {
camera.stopPreview();
}
// Pause game or animation
if (gameEngine != null) {
gameEngine.pause();
}
// Stop sensor monitoring
sensorManager.unregisterListener(this);
// Save user progress
saveUserProgress();
// Commit any pending changes
SharedPreferences.Editor editor = preferences.edit();
editor.putString("last_action", getCurrentAction());
editor.apply();
}
Common Tasks:
- Pause CPU-intensive operations
- Save user data and preferences
- Release camera and sensors
- Pause audio/video playback
- Stop location updates
5. onStop() - Activity Becomes Hidden
Purpose: Activity is no longer visible to the user.
Characteristics:
- Activity is completely hidden
- Another activity has taken full screen
- Should stop all visual updates
- Release resources that aren't needed
Implementation:
@Override
protected void onStop() {
super.onStop();
// Unregister broadcast receivers
if (batteryReceiver != null) {
unregisterReceiver(batteryReceiver);
}
// Stop background services if not needed
if (backgroundService != null) {
stopService(new Intent(this, BackgroundService.class));
}
// Close database connections
if (database != null) {
database.close();
}
// Stop network requests
if (networkRequestQueue != null) {
networkRequestQueue.cancelAll(REQUEST_TAG);
}
}
Common Tasks:
- Stop animations and UI updates
- Release heavy resources
- Cancel network requests
- Unregister receivers
- Close database connections
6. onDestroy() - Activity Destruction
Purpose: Final cleanup before activity is destroyed.
Characteristics:
- Activity is being destroyed
- Last chance to clean up resources
- Called when activity is finishing or system is killing it
- After this, activity object is garbage collected
Implementation:
@Override
protected void onDestroy() {
super.onDestroy();
// Release all resources
if (mediaPlayer != null) {
mediaPlayer.release();
mediaPlayer = null;
}
// Close any open streams
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// Clear references to prevent memory leaks
backgroundHandler = null;
adapter = null;
Log.d(TAG, "Activity destroyed");
}
Common Tasks:
- Release media players
- Close file streams
- Clear static references
- Cancel background threads
- Final cleanup
7. onRestart() - Activity Restart
Purpose: Called when activity is restarting after being stopped.
Characteristics:
- Only called after onStop()
- Followed by onStart()
- Chance to reinitialize stopped resources
Implementation:
@Override
protected void onRestart() {
super.onRestart();
// Reinitialize components that were stopped
initializeStoppedComponents();
// Refresh data that might be stale
refreshDataFromServer();
Log.d(TAG, "Activity restarting");
}
State Transition Scenarios
Normal Launch
- onCreate() → onStart() → onResume() → [RUNNING]
User Presses Home Button
- [RUNNING] → onPause() → onStop()
User Returns to App
- onRestart() → onStart() → onResume() → [RUNNING]
Phone Call Received
- [RUNNING] → onPause() → onResume() → [RUNNING]
App is Finished
- [RUNNING] → onPause() → onStop() → onDestroy()
Best Practices
Resource Management
- Initialize in onCreate(): Set up static resources
- Start in onResume(): Begin active operations
- Pause in onPause(): Save critical data
- Stop in onStop(): Release heavy resources
- Clean in onDestroy(): Final cleanup
Performance Optimization
- Quick onPause(): Keep onPause() fast for smooth transitions
- Save State: Always save user data in onPause()
- Lazy Loading: Initialize expensive resources only when needed
- Memory Management: Release references to prevent leaks
User Experience
- Seamless Transitions: Ensure smooth activity transitions
- State Preservation: Maintain user context across lifecycle
- Background Awareness: Handle background/foreground gracefully
- Error Handling: Graceful handling of lifecycle interruptions
The Android Activity Lifecycle ensures efficient resource management and optimal user experience by providing clear hooks for developers to manage their application's behavior throughout its execution.